package logging

import (
	"io"
	"os"

	"github.com/sirupsen/logrus"
	"gopkg.in/natefinch/lumberjack.v2"
)

var Logger *logrus.Logger

type LogSettings struct {
	LogFile    string `yaml:"log_file"`
	MaxSize    int    `yaml:"max_size"`
	MaxBackups int    `yaml:"max_backups"`
	MaxAge     int    `yaml:"max_age"`
}

func SetLogger(ls *LogSettings, debug bool) {
	if ls == nil {
		//default  20M,
		ls = &LogSettings{
			LogFile:    "/var/log/server.log",
			MaxSize:    20,
			MaxBackups: 4,
			MaxAge:     2,
		}
	}
	logWriter := &lumberjack.Logger{
		Filename:   ls.LogFile,
		MaxSize:    ls.MaxSize,
		MaxBackups: ls.MaxBackups,
		MaxAge:     ls.MaxAge,
	}

	logrus.SetReportCaller(true)
	logrus.SetFormatter(&logrus.JSONFormatter{})
	logrus.RegisterExitHandler(func() {
		_ = logWriter.Close()
	})

	var w io.Writer
	if debug {
		w = io.MultiWriter(os.Stdout, logWriter)
	} else {
		w = io.Writer(logWriter)
	}
	logrus.SetOutput(w)
}

func GetLogger() *logrus.Logger {
	return logrus.StandardLogger()
}
func init() {
	Logger = logrus.StandardLogger()
}
